package modules::tophat;
use modules::utilities;
use Data::Dumper;
use v5.10;
sub new {
  my ($class,$config) = @_;
  say 'tophat-1.4.0';
  my $tophat_conf   = "/usr/users/ga002/corpasm/workarea/src/conf/tophat.conf";
  my $util          = modules::utilities->new();
  my $self = {
               _path         => $config->{'PATH'       },
               _job_name     => $config->{'JOB_NAME'   },
               _genome       => $config->{'GENOME'     },
               _gtf_file     => $config->{'GTF_FILE'   },
               _fastq_dir    => $config->{'FASTQ_DIR'  },
               _no_replicas  => $config->{'NO_REPLICAS'},
               _no_samples   => $config->{'NO_SAMPLES' },
               _samples      => $config->{'SAMPLES'    },
               _tophat_conf  => $util->read_conf_file($tophat_conf,'tophat_conf'),
             };
  bless $self,$class;

  return $self;
}

sub prepare {
  my ($self) = @_;
  my $samples            = $self->{'_samples'   };
  my $path               = $self->{'_path'      };
  my $job_name           = $self->{'_job_name'  };
  my $no_samples         = $self->{'_no_samples'};
  my $job_dir            = $path       . '/results/' . $job_name;
  my $tophat_out         = $job_dir    . "/TopHat/"  ;
    
  mkdir  $job_dir   , 0777 unless(-d $job_dir   ); chmod(0777, $job_dir   );

  mkdir  $tophat_out, 0777 unless(-d $tophat_out); chmod(0777, $tophat_out);
  $self->{'_tophat_out'} = $tophat_out;

  foreach my $sample(@$samples){
    my    $sample_dir = $tophat_out ."/". $sample->[0];
    mkdir $sample_dir, 0777 unless(-d $sample_dir);
    print "Creating directory '$sample_dir'...\n"; 
    chmod(0777, $sample_dir);
  }
  
  return;
}

sub run {
  my $self = shift;
  my $samples            = $self->{'_samples'     };
  my $path               = $self->{'_path'        };
  my $genome             = $self->{'_genome'      };
  my $fastq_dir          = $self->{'_fastq_dir'   };
  my $gtf_file           = $self->{'_gtf_file'    };
  my $tophat_out         = $self->{'_tophat_out'  };
  my $tophat_conf        = $self->{'_tophat_conf' };

  my $i=1;
  foreach my $sample(@$samples) { 
    my    $cmd  =  qq(bsub -J tophat_$i -n 4 -R "span[ptile=4] rusage[mem=5000]" )
                .  qq(tophat-1.4.0 tophat -p 8 -G $gtf_file -o $tophat_out/$sample->[0] );
    map { $cmd  .= qq($_ $tophat_conf->{$_} )   }  keys %$tophat_conf; # map each option
    map { $cmd  .= qq($genome $fastq_dir/$_.fastq  )    }  @$sample; # map each replica to the command
    print "\n\nRUNNING COMMAND:\n$cmd\n\n";
    system($cmd);
    $i++;
  }
=pod
  my $wait = 1;
  while ($wait == 1) {
    my  @info = qx(bjobs);
    print scalar localtime() . "\n";
    if(my @tophat_jobs = grep(/tophat_/, @info) ) { map{print $_}@tophat_jobs; sleep 10 }
    else {$wait = 0}  
  }
=cut
  return;
}
1; 
